package com.qf.chinatelcom.smsatragety.stragety;

import com.qf.chinatelcom.smsatragety.cache.LimitLocalCache;
import com.qf.chinatelcom.smsatragety.feign.CacheService;
import com.qf.chinatelcom.smsatragety.filter.DuTyFilter;
import com.qianfeng.smsplatform.common.constants.InterfaceExceptionDict;
import com.qianfeng.smsplatform.common.model.Standard_Submit;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.Instant;
import java.util.Map;

@Component
public class LimitsFilter implements DuTyFilter {

    private static final Logger LOGGER = LoggerFactory.getLogger(LimitsFilter.class);

    private CacheService cacheService;

    @Autowired
    public void setCacheService(CacheService cacheService) {
        this.cacheService = cacheService;
    }

    private LimitLocalCache limitLocalCache;

    @Autowired
    public void setLimitLocalCache(LimitLocalCache limitLocalCache) {
        this.limitLocalCache = limitLocalCache;
    }

    @Override
    public boolean dealSms(Standard_Submit submit) {
        System.err.println("限流开始处理了");
        //获取到所有的限流规则
        Instant instant = Instant.now();//获取到当前的时间作为结束时间
        Map<Integer, Integer> limitList = limitLocalCache.getLimitList();//获取到所有的限流策列
        for (Map.Entry<Integer, Integer> entry : limitList.entrySet()) {
            Integer key = entry.getKey();//获取到时间
            Integer value = entry.getValue();//获取到值
            Instant seconds = instant.plusSeconds(-key);//开始的时间
            //以当前时间为终点，以向前推的时间为起点，查询这个客户，对这个手机号发送的短信数量
            Long byScore = cacheService.getSizeByScore(submit.getClientID() + submit.getDestMobile(), seconds.getEpochSecond(), instant.getEpochSecond());

            if(byScore>=value){
                //但凡有一个策略不符合，我们就退出
                LOGGER.error("当前手机号的发送频率超过限制,限制策列为{}秒内允许发送{}",key,value);
                submit.setDescription("当前手机号:"+submit.getDestMobile()+"发送频率过于频繁");
                submit.setErrorCode(InterfaceExceptionDict.RETURN_STATUS_LIMIT_ERROR+"");//失败的原因
                submit.setReportState(2);//失败的标识为
                return false;
            }

        }
        //整个循环没有结束的话，我们就把手机号作为分数当作key和value保存起来，作为value 的主要原因是value不能重复，否则分数会丢失一个
        LOGGER.error("没有超过");
        cacheService.add2Zset(submit.getClientID()+submit.getDestMobile(),instant.getEpochSecond()+"",instant.getEpochSecond());
        return true;
    }
}
